var map; //地图对象
var grahpiclayer;
require(["esri/map", "tdlib/TDTLayer", "tdlib/TDTLayer",
    "tdlib/TDTAnnoLayer",
    "esri/layers/GraphicsLayer", "esri/symbols/SimpleMarkerSymbol", "esri/graphic", "esri/geometry/Point", "esri/InfoTemplate",
    "dojo/domReady!"
], function(Map, TDTLayer, TDTILayer, TDTAnnoLayer,
    GraphicsLayer, SimpleMarkerSymbol, Graphic, Point, InfoTemplate) {
    map = new Map("map", {
        center: [105.5719395801757, 30.51760675785775],
        zoom: 11,
        logo: false,
    });

    var basemap = new TDTLayer();
    var _basemap = new TDTLayer();
    //basemap.visible = false;
    map.addLayer(basemap);
    var basemap_image = new TDTILayer();
    var _basemap_image = new TDTILayer();
    //map.addLayer(basemap_image);
    var annolayer = new TDTAnnoLayer();
    map.addLayer(annolayer);

    $('#map').startViewMap({ map: map, baselayer: _basemap });

    //地图点击事件
    map.on("click", function(evt) {
        //console.log(evt.mapPoint.x + "  " + evt.mapPoint.y);
    });
    //测量 polygon polyline
    // var measure = new measureMap({ map: map, type: 'polygon', isMeasure: false });
    // measure.createToolbar();
    // measure.activateToolbar();

    //加载graphic图层 测试用
    grahpiclayer = new GraphicsLayer();
    map.addLayer(grahpiclayer);
    var pt = new Point(105.5719395801757, 30.51760675785775, map.spatialReference);
    var symbol = new esri.symbol.PictureMarkerSymbol("./img/nornal.png", 48, 48);
    var infoTemplate = new InfoTemplate("详情", "这是一个地图要素");
    var gra = new Graphic(pt, symbol, null, infoTemplate);
    grahpiclayer.add(gra);
    //测试框选
    var Graphics;
    //squareSelect("line", map, grahpiclayer);
    //测试画框框选
    //squareSelect("polygon", map, grahpiclayer) //
});

//测试测量 绘制
function celiangtest(map, type, isMeasure) {
    var measure = new measureMap({ map: map, type: type, isMeasure: isMeasure });
    measure.createToolbar();
    measure.activateToolbar();
}
//回到初始视图
function baseView() {
    map.centerAndZoom([105.5719395801757, 30.51760675785775], 11);
}
//框选 某图层的要素 type:polygon or line
function squareSelect(type, map, _graphicLayer, Graphics) {
    var arry = [];
    require([
        "esri/toolbars/draw", "esri/layers/GraphicsLayer", "esri/symbols/SimpleFillSymbol", "esri/Color", "esri/graphic", "esri/geometry/Polygon"
    ], function(Draw, GraphicsLayer, SimpleFillSymbol, Color, Graphic, Polygon) {
        draw = new Draw(map); //toolbar.activate(Draw[tool])
        draw.activate(type);
        draw.on("draw-end", function(event) {
            var geometry = event.geometry;
            //debugger;
            arry = [];
            if (type == "line") {
                var grahpiclayer = new GraphicsLayer();
                map.addLayer(grahpiclayer);
                var symbol = new SimpleFillSymbol();
                var x1 = geometry.paths[0][0][0];
                var y1 = geometry.paths[0][0][1];
                var x2 = geometry.paths[0][1][0];
                var y2 = geometry.paths[0][1][1];
                var xmin, ymin, xmax, ymax;
                if (x1 > x2) {
                    xmax = x1;
                    xmin = x2;
                } else {
                    xmax = x2;
                    xmin = x1;
                }
                if (y1 > y2) {
                    ymax = y1;
                    ymin = y2;
                } else {
                    ymax = y2;
                    ymin = y1;
                }
                var polygonJson = {
                    "rings": [
                        [
                            [xmin, ymin],
                            [xmax, ymin],
                            [xmax, ymax],
                            [xmin, ymax],
                            [xmin, ymin]
                        ]
                    ],
                    "spatialReference": { "wkid": 4326 }
                };
                var polygon = new Polygon(polygonJson);
                geometry = polygon;
                var gra = new Graphic(polygon, symbol);
                grahpiclayer.add(gra);
                setTimeout(function() {
                    map.removeLayer(grahpiclayer);
                }, 1000);
            }
            var graphics = _graphicLayer.graphics;

            if (graphics.length > 0) {
                for (var i = 0; i < graphics.length; i++) {
                    var obj = graphics[i];
                    var bool = geometry.contains(obj.geometry);
                    if (bool) {
                        arry.push(obj.geometry);
                    }
                }
                console.log("选中了" + arry.length + "个要素");
                console.log(arry);
                layer.msg("选中了" + arry.length + "个要素", { icon: 6 });
            }
            //
            draw.deactivate();
        });
    })
}
//精准点测量
function zoomToPoint(opt, zoom) {
    var x = parseFloat(document.getElementById('xx').value);
    var y = parseFloat(document.getElementById('yy').value);
    var zoom = parseInt(document.getElementById('zoom').value);
    //var x = parseFloat(opt.x);
    //var y = parseFloat(opt.y);
    //var map = opt.map;
    map.centerAndZoom({ x: x, y: y }, zoom);
}
//绘制测量
//opt.map
//opt.measureType
//opt.isMeasure
function measureMap(opt) {
    var opt = opt;
    var map = opt.map;
    var type = opt.type;
    var isMeasure = opt.isMeasure;
    var toolbar = {};
    var draw;
    var graphiclayer;
    //创建
    toolbar.createToolbar = function() {
            //var that = this;
            require([
                "esri/toolbars/draw"
            ], function(Draw) {
                draw = new Draw(map); //toolbar.activate(Draw[tool])
                draw.on("draw-end", addToMap);
            })
        }
        //激活
    toolbar.activateToolbar = function() {
            setTimeout(function() {
                draw.activate(type);
            }, 1000);
        }
        //移除
    toolbar.deactivateToolbar = function() {
        draw.deactivate();
        map.removeLayer(graphiclayer);
    }
    var addToMap = function(event) {
            require([
                "esri/symbols/SimpleMarkerSymbol",
                "esri/symbols/SimpleLineSymbol",
                "esri/symbols/SimpleFillSymbol",
                "esri/geometry/geometryEngine", "esri/symbols/TextSymbol", "esri/Color", "esri/symbols/Font", "esri/layers/GraphicsLayer"
            ], function(SimpleMarkerSymbol, SimpleLineSymbol, SimpleFillSymbol, geometryEngine, TextSymbol, Color, Font, GraphicsLayer) {
                var symbol;
                //toolbar.deactivate();
                graphiclayer = new GraphicsLayer();
                map.addLayer(graphiclayer);
                var text = "";
                var point;
                switch (event.geometry.type) {
                    case "point":
                        symbol = new SimpleMarkerSymbol();
                        break;
                    case "multipoint":
                        symbol = new SimpleMarkerSymbol();
                        break;
                    case "polyline":
                        symbol = new SimpleLineSymbol();
                        break;
                    default:
                        symbol = new SimpleFillSymbol();
                        break;
                }
                var graphic = new esri.Graphic(event.geometry, symbol);
                graphiclayer.add(graphic);

                if (isMeasure) {
                    var geom = event.geometry;
                    switch (geom.type) {
                        case "polyline":
                            geom.spatialReference = {
                                wkid: 4326
                            };
                            text = geometryEngine.geodesicLength(geom, "meters");
                            if (text > 1000) {
                                text = (text / 1000).toFixed(2) + "千米";
                            } else {
                                text = text.toFixed(2) + "米";
                            }
                            var paths = geom.paths;
                            point = new esri.geometry.Point(paths[0][paths[0].length - 1][0], paths[0][paths[0].length - 1][1]);
                            break;
                        default:
                            geom.spatialReference = {
                                wkid: 4326
                            };
                            text = geometryEngine.geodesicArea(geom, "square-meters");
                            if (text > 1000000) {
                                text = (text / 1000000).toFixed(2) + "平方千米";
                            } else {
                                text = text.toFixed(2) + "平方米";
                            }
                            var rings = geom.rings;
                            point = new esri.geometry.Point(rings[0][rings[0].length - 2][0], rings[0][rings[0].length - 2][1]);
                            break;
                    }

                    var font = new Font();
                    font.setSize('12pt');
                    font.setWeight(Font.WEIGHT_BOLD);
                    var textymbol = new TextSymbol(text).setColor(new Color([0, 0, 0])).setOffset(0, 0).setFont(font);
                    var textgraphic = new esri.Graphic(point, textymbol);
                    graphiclayer.add(textgraphic);
                }
            });

            draw.deactivate();
        }
        //toolbar.createToolbar();
    return toolbar;
}


//鹰眼
(function($) {
    var defaults = {
        basemap: null,
        graphiclayer: null,
        baselayer: null,
        width: 300,
        height: 200,
        bottom: 0,
        left: 0,
        position: 'absolute',
        id: 'overview_map',
        tip: true,
        ifmove: false
    };
    //��չ
    $.fn.extend({
        //�������
        startViewMap: function(options) {
            //����Ĭ�ϲ���
            var opts = $.extend(defaults, options);
            //����html�ĵ�
            function createDom() {
                var id = opts.map.id;
                var overviewid = 'overview_' + id;
                opts.id = overviewid;
                var arrowid = 'overviewarrow_' + id;
                var html = "<div id='" + overviewid + "'></div>";
                html += '<div id="' + arrowid + '" style="position: absolute; bottom: 3px; left: 0; z-index: 99; width: 20px; height: 20px;">' +
                    '<img src="css/show.png" style="width: 20px; height: 20px;cursor: pointer">' +
                    '</div>';
                $('#' + id).after(html);
                $('#' + overviewid).css('position', opts.position);
                $('#' + overviewid).css('bottom', opts.bottom);
                $('#' + overviewid).css('left', opts.left);
                $('#' + overviewid).css('width', opts.map.width / 6);
                $('#' + overviewid).css('height', opts.map.height / 6);
                $('#' + overviewid).css('border', "2px solid #dedede");
                $('#' + overviewid).css('background-color', "#dedede");
                $('#' + arrowid).on('click', function() {
                    if ($("#" + overviewid).css('display') == 'block') {
                        $("#" + overviewid).hide();
                        $('#' + arrowid + ' img').attr('src', 'css/hide.png');
                    } else {
                        $("#" + overviewid).show();
                        $('#' + arrowid + ' img').attr('src', 'css/show.png');
                    }
                });
            }
            //������
            return this.each(function() {
                createDom();
                require(["esri/map", "esri/graphic", "esri/layers/GraphicsLayer", "esri/graphicsUtils"],
                    function(Map, Graphic, GraphicsLayer, graphicsUtils) {
                        opts.basemap = new Map(opts.id, {
                            center: [104, 30],
                            zoom: 5,
                            slider: false,
                            logo: false
                        });
                        opts.basemap.addLayer(opts.baselayer);
                        opts.basemap.disableDoubleClickZoom();
                        opts.basemap.disableRubberBandZoom();
                        opts.basemap.disableScrollWheelZoom();
                        opts.basemap.disableShiftDoubleClickZoom();
                        opts.graphiclayer = new GraphicsLayer();
                        opts.basemap.addLayer(opts.graphiclayer);

                        function setOverViewMapExtent() {
                            if (opts.tip) {
                                opts.graphiclayer.clear();
                                var geometry = new Graphic();
                                geometry.geometry = opts.map.extent;
                                geometry.symbol = new esri.symbol.SimpleFillSymbol();
                                opts.graphiclayer.add(geometry);
                                if (opts.graphiclayer.graphics) {
                                    var myExtent = graphicsUtils.graphicsExtent(opts.graphiclayer.graphics);
                                    opts.basemap.setExtent(myExtent.expand(2));
                                }
                            }
                            opts.tip = true;
                        }
                        setOverViewMapExtent();
                        opts.map.on('extent-change', function() {
                            setOverViewMapExtent();
                        });

                        function addMoveGraphic(evt) {
                            opts.tip = false;
                            var polygon = opts.graphiclayer.graphics[0].geometry;
                            var extent = new esri.geometry.Extent(polygon);
                            var point = extent.getCenter();
                            var width = evt.mapPoint.x - point.x;
                            var height = evt.mapPoint.y - point.y;
                            var xmin = extent.xmin + width;
                            var xmax = extent.xmax + width;
                            var ymin = extent.ymin + height;
                            var ymax = extent.ymax + height;
                            var geo = new esri.geometry.Extent(xmin, ymin, xmax, ymax, opts.basemap.spatialReference);
                            opts.graphiclayer.clear();
                            var graphic = new Graphic();
                            graphic.geometry = geo;
                            graphic.symbol = new esri.symbol.SimpleFillSymbol();
                            opts.graphiclayer.add(graphic);
                            opts.basemap.centerAt(point);
                            opts.map.centerAt(point);
                        }
                        opts.graphiclayer.on("mouse-over", function() {
                            if (opts.ifmove) {
                                opts.basemap.disablePan();
                            } else {
                                opts.ifmove = true;
                                opts.basemap.disablePan();
                            }
                        });
                        opts.graphiclayer.on("mouse-out", function() {
                            if (opts.ifmove) {
                                opts.ifmove = false;
                                opts.basemap.enablePan();
                            }
                        });
                        opts.basemap.on("mouse-drag", function(evt) {
                            if (opts.ifmove) {
                                addMoveGraphic(evt);
                            }
                        });
                        opts.basemap.on("click", function(evt) {
                            addMoveGraphic(evt);
                        });
                        opts.basemap.on("mouse-drag-end", function(evt) {
                            if (opts.ifmove) {
                                addMoveGraphic(evt);
                            }
                        });
                    });
            });
        }
    });
})(jQuery);